<template>
  <n-card :bordered="false">
    <n-alert type="info" class="alert_small m-b-10">
      温馨提示：1.管理用户等级，系统默认等级不能删除；2.删除用户等级时，会重新调整用户等级为系统默认等级，请谨慎操作。
    </n-alert>
    <DataTable
        ref="level_lists"
        :columns="columns"
        :action-column="actionColumn"
        :row-key="(row:Recordable) => row.id"
        list-url="user/level_list"
        default-serial-number serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['user:level:add']" @click="()=>(addEditUserLevel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </DataTable>

  </n-card>
  <!--新增、修改用户等级-->
  <n-modal v-model:show="addEditUserLevel"
           :title="addEditUserLevelForm.id?'修改用户等级':'新增用户等级'"
           :mask-closable="false"
           :show-icon="false"
           preset="dialog"
           style="width: 590px"
           @after-leave="closeAddEditUserLevel">
    <n-form ref="user_leve_form_ref"
            :model="addEditUserLevelForm"
            :rules="addEditUserLevelFormRules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="left">
      <n-form-item label="等级级别" path="level">
        <div style="width: 100%">
          <div style="width: 200px">
            <n-select v-model:value="addEditUserLevelForm.level" :options="levelOption" placeholder="请选择等级级别"
                     :disabled="addEditUserLevelForm.is_disabled" clearable/>
          </div>
          <p class="tips_p">
            数字越大表示等级越高，等级权重不能相同。填写大于1的整数
          </p>
        </div>
      </n-form-item>
      <n-form-item label="等级名称" path="name">
        <n-input v-model:value="addEditUserLevelForm.name" placeholder="请填写等级名称" clearable/>
      </n-form-item>
      <n-form-item label="等级名称(维)" path="name_uy">
        <n-input v-model:value="addEditUserLevelForm.name_uy" class="uy" placeholder=" دەرىجە نامنى تولدۇرۇڭ"
                 clearable/>
      </n-form-item>
      <n-form-item label="等级条件" path="order_total" v-if="!addEditUserLevelForm.is_disabled">
        <n-input-group>
          <n-input-group-label>累计完成订单金额满</n-input-group-label>
          <n-input-number v-model:value="addEditUserLevelForm.order_total" placeholder="请输入金额" :min="0"
                          :style="{ width: '50%' }" :show-button="false" clearable/>
          <n-input-group-label>元</n-input-group-label>
        </n-input-group>
      </n-form-item>
      <n-form-item label="等级折扣" path="discount">
        <div>
          <n-radio-group v-model:value="addEditUserLevelForm.p_discount" name="radiogroup"
                         style="display: flex;width: 100%;align-items: center;">
            <n-radio :value="0" label="无等级折扣"/>
            <n-radio :value="1">参与等级折扣</n-radio>
            <div>
              <n-input-group ref="discount_ref">
                <n-input-number v-model:value="addEditUserLevelForm.discount" :max="10" style="width: 150px"
                                placeholder="请填写折扣" :min="0" :show-button="false" clearable/>
                <n-input-group-label>折</n-input-group-label>
              </n-input-group>
            </div>
          </n-radio-group>
          <p class="tips_p">
            填写0.1到10之间的数字，可以保留小数点2位数字
          </p>
        </div>
      </n-form-item>
      <n-form-item label="等级图标" path="src">
        <div>
          <div class="select-level-img" ref="level_img" :class="appStore.theme=='light'?'light-img':'dark-img'">
            <div class="select-level-img-clear" v-if="addEditUserLevelForm.src"
                 @click.stop="()=>(addEditUserLevelForm.src='',addEditUserLevelForm.src_path='')">
              <n-icon :size="16">
                <Close/>
              </n-icon>
            </div>
            <div class="select-level-img-img" @click.stop="()=>(show_img_select=true)">
              <template v-if="addEditUserLevelForm.src">
                <img :src="addEditUserLevelForm.src_path" style="object-fit: contain;width: 100%;height: 100%" alt="">
              </template>
              <template v-else>
                <p style="margin-block-start: 0;margin-block-end: 0;">添加图片</p>
              </template>
            </div>
          </div>
          <p class="tips_p">
            建议尺寸：100*100像素，jpg，jpeg，png图片类型
          </p>
        </div>
      </n-form-item>
      <n-form-item label="等级描述" path="describe">
        <n-input
            v-model:value="addEditUserLevelForm.describe"
            type="textarea"
            placeholder="请填写等级描述"
            :autosize="{minRows: 3}"/>
      </n-form-item>
      <n-form-item label="状态" path="status" :show-feedback="false">
        <n-switch v-model:value="addEditUserLevelForm.status" :round="false" :checked-value="1" :unchecked-value="0">
          <template #checked>
            启用
          </template>
          <template #unchecked>
            禁用
          </template>
        </n-switch>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addEditUserLevel=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitUserLeveLoading" @click="handelSubmitUserLeve">确定</n-button>
      </n-space>
    </template>
  </n-modal>
  <!--图片列表-->
  <ImgContent v-model:show="show_img_select" @update:select="selectedImg"/>
</template>

<script setup lang="ts">
import {ref, onBeforeMount, onMounted, reactive, h} from 'vue'
import {FormInst, FormItemRule, NIcon, NImage, NTag, NPopconfirm, useMessage} from 'naive-ui';
import {UseAppStore} from '@/stores/app.ts';
import {Close} from '@vicons/ionicons5';
import ImgContent from "@components/ImgContent";
import {errBorderColor} from '@/util'
import {postPutRequest, delRequest} from '@/api/data.ts';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import DataTable from "@components/DataTable";
import {AddSharp} from "@vicons/material";

const appStore = UseAppStore();
const message = useMessage()
const show_img_select = ref<boolean>(false);

//数据表ref
const level_lists = ref<any>();
//数据表
const columns = ref([
  {
    title: '等级级别',
    key: 'level_text',
    width: 130,
  },
  {
    title: '等级名称',
    key: 'name',
    width: 150,
  }, {
    title: '等级名称(维)',
    key: 'name_uy',
    width: 170,
    align: 'center',
    render(row: { name_uy: string }) {
      return h('span', {
        className: 'uy'
      }, {default: () => (row.name_uy)})
    }
  }, {
    title: '等级图标',
    key: 'src',
    width: 100,
    align: 'center',
    render(row: { src: string, web_site: string }) {
      return h(NImage, {
        width: 20,
        height: 20,
        src: row.web_site + row.src
      })
    }
  }, {
    title: '等级折扣',
    key: 'discount',
    width: 100,
    align: 'center',
    render(row: { discount: number }) {
      return h('span', null,{ default: () => (row.discount+'折')})
    }
  }, {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center',
    render(row: { status: boolean }) {
      const enabled_color = row.status ? 'success' : 'error';
      const enabled_text = row.status ? '启用' : '禁用';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  },{
    title: '等级描述',
    key: 'describe',
  }, {
    title: '创建时间',
    key: 'create_time',
    width: 175,
  }
]);
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    // @ts-ignore
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['user:level:edit']
        },
        {
          label: '删除',
          type: "error",
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前用户等级吗？',
          },
          permission: ['user:level:del'],
          disabled: !!record.is_disabled,
        },
      ],
    });
  },
});


const levelOption = ref<{ label: string | number, value: string | number }[]>([]);
const addEditUserLevel = ref<boolean>(false);
const handelSubmitUserLeveLoading = ref<boolean>(false);
const user_leve_form_ref = ref<FormInst | null>(null);
const level_img = ref<HTMLElement>();
const discount_ref = ref<HTMLElement>();
const addEditUserLevelForm = ref({
  id: 0,
  name: '',
  name_uy: '',
  level: null,
  order_total: null,
  p_discount: 0,
  discount: 10,
  describe: '',
  status: 1,
  src: '',
  src_path: '',
  is_disabled: false,
});

//新增、修改验证器
const addEditUserLevelFormRules = ref({
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写会员等级名称'
  },
  level: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请填选择等级级别'
  },
  describe: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请填写会员等级描述'
  },
  discount: {
    required: true,
    trigger: ['blur', 'change'],
    validator: (_rule: FormItemRule, value: string, callback: Function) => {
      if (addEditUserLevelForm.value.p_discount === 1 && value == null) {
        callback('请填写参与折扣');
      } else {
        callback();
      }
    }
  },
  src: {
    required: true,
    trigger: 'change',
    validator: (_rule: FormItemRule, value: string, callback: Function) => {
      if (!value) {
        callback('请添加等级图标');
        errBorderColor(level_img.value);
      } else {
        errBorderColor(level_img.value, true);
        callback();
      }
    }
  },
  order_total: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请填写等级条件'
  }
})
//修改用户等级
const handleEdit = (record: Recordable) => {
  addEditUserLevelForm.value.id = record.id;
  addEditUserLevelForm.value.name = record.name;
  addEditUserLevelForm.value.name_uy = record.name_uy;
  addEditUserLevelForm.value.level = record.level;
  addEditUserLevelForm.value.order_total = record.order_total;
  addEditUserLevelForm.value.p_discount = record.p_discount;
  addEditUserLevelForm.value.discount = parseFloat(record.discount);
  addEditUserLevelForm.value.describe = record.describe;
  addEditUserLevelForm.value.status = record.status;
  addEditUserLevelForm.value.src = record.src;
  addEditUserLevelForm.value.src_path = record.web_site + record.src;
  addEditUserLevelForm.value.is_disabled = record.is_disabled;
  addEditUserLevel.value = true;
}
//删除用户等级
const handleDelete = (record: Recordable) => {
  delRequest('user/level_del', {id: record.id}).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          level_lists.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//关闭新增、修改模态框
const closeAddEditUserLevel = () => {
  addEditUserLevelForm.value.id = 0;
  addEditUserLevelForm.value.name = '';
  addEditUserLevelForm.value.name_uy = '';
  addEditUserLevelForm.value.level = null;
  addEditUserLevelForm.value.order_total = null;
  addEditUserLevelForm.value.p_discount = 0;
  addEditUserLevelForm.value.discount = 10;
  addEditUserLevelForm.value.describe = '';
  addEditUserLevelForm.value.status = 1;
  addEditUserLevelForm.value.src = '';
  addEditUserLevelForm.value.src_path = '';
  addEditUserLevelForm.value.is_disabled = false
  handelSubmitUserLeveLoading.value = false;
}
//提交数据
const handelSubmitUserLeve = (e: MouseEvent) => {
  e.preventDefault();
  user_leve_form_ref.value?.validate((errors) => {
    if (!errors) {
      handelSubmitUserLeveLoading.value = true;
      const url = addEditUserLevelForm.value.id ? 'user/level_edit' : 'user/level_add';
      postPutRequest(url, addEditUserLevelForm.value).then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditUserLevel.value = false;
              if (addEditUserLevelForm.value.id) {
                level_lists.value.reload();
              } else {
                level_lists.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitUserLeveLoading.value = false;
        }
      })
    }
  })
}
//已选中图片
const selectedImg = (img_s: Array<{ src: string, full_src: string }>) => {
  addEditUserLevelForm.value.src = img_s[0].src;
  addEditUserLevelForm.value.src_path = img_s[0].full_src;
}
onMounted(() => {

})
const createLevelOption = async () => {
  const res: Array<{ label: string | number, value: string | number }> = [];
  for (let i = 1; i < 51; i++) {
    res.push({label: i, value: i})
  }
  levelOption.value = res;
}
onBeforeMount(() => {
  //生成用户等级
  createLevelOption();
})
</script>

<style scoped lang="scss">
.discount-style {
  height: 32px;
  display: flex;
  align-items: center;
}

.select-level-img {
  position: relative;
  width: 70px;
  height: 70px;
  border-radius: var(--n-border-radius);
  cursor: pointer;

  &-clear {
    width: 16px;
    height: 16px;
    position: absolute;
    top: -7px;
    z-index: 10;
    right: -7px;
    background-color: rgba(0, 0, 0, .3);
    color: #ffffff;
    border-radius: 50%;
    cursor: pointer;
    display: none;
  }

  &-img {
    width: 100%;
    height: 100%;
    display: flex;
    overflow: hidden;
    justify-content: center;
    align-items: center;
  }
}

.select-level-img:hover {
  .select-level-img-clear {
    display: block;
  }
}

</style>